/*
    Copyright (C) 2006  Brano Kemen

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "coid/comm/str.h"
#include "coid/comm/dir.h"
#include "coid/comm/binstream/stdstream.h"

using namespace coid;


static int Gloop = 0;

extern "C" {
int coid_server_start( int& port, int (*cancel_cbk)(int) );
int coid_server_stop();
int coid_get_version( charstr& );
} //extern "C"

////////////////////////////////////////////////////////////////////////////////
int cancel_request( int restart )
{
    if( restart )
    {
        //spawn another
    }

    Gloop = 0;
    return 0;
}

//
stdoutstream sout;

////////////////////////////////////////////////////////////////////////////////
int main( int argc, char* argv[] )
{
    int port = 0;

    for( int i=1; i < argc; i++ )
    {
        token arg = argv[i];
        if( arg == "-v"  ||  arg == "--version" )
        {
            charstr ver;
            if( 0 == coid_get_version(ver) )
                sout << ver << BINSTREAM_FLUSH;
            else
                sout << "version unknown" << BINSTREAM_FLUSH;
            return 0;
        }
        else if( arg == "-p"  ||  arg == "--port" )
        {
            ++i;
            token portnum = token::empty();
            if(i<argc)
                portnum = argv[i];

            port = portnum.touint_and_shift();
            if( port <= 0  ||  port >= 0x10000  ||  !portnum.is_empty() ) {
                sout << "invalid port number" << BINSTREAM_FLUSH;
                return -1;
            }
        }
        else {
            sout << "unrecognized argument: " << arg << BINSTREAM_FLUSH;
            return -2;
        }
    }

    if(!port)
        port = 55099;

    if( 0 == coid_server_start( port, &cancel_request ) )
    {
        Gloop = 1;
        while( Gloop )
        {
            coid::sysSleep(1);
        }

        coid_server_stop();
    }

    return 0;
}

